import React from "react";
import _ from 'lodash';
import type { FieldData } from "rc-field-form/lib/interface";

export interface IFormMonitorValuesOptions<T> {
    onChange?: (values: T) => void
}

/** 监听form字段变化事件，维护values属性 */
export function useFormMonitorValues<T = any>(options?: IFormMonitorValuesOptions<T>) {

    const { onChange } = options || {};
    const [allFields, setAllFields] = React.useState<FieldData[]>([]);
    const [values, setValues] = React.useState<T>({} as T);

    const onFieldsChange = React.useCallback((_changedFields: FieldData[], allFields: FieldData[]) => {
        setAllFields(allFields);
    }, []);

    React.useEffect(() => {
        let v: any = {};
        allFields.forEach(field => {
            if (typeof field.name === 'string') {
                v[field.name] = field.value;
            } else if (Array.isArray(field.name)) {
                v = _.set(v, field.name, field.value);
            }
        });
        setValues(v);
        onChange?.(v);
    }, [allFields, onChange]);

    return {
        /** form 字段变化事件 */
        onFieldsChange,

        /** 所有字段 */
        allFields,

        /** 表单数据 */
        values,

        setValues,
    }
}





